using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using SumerCoreDevOps.Infrastructure.Data;
using SumerCoreDevOps.Infrastructure.Workflow;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Shared.Models;

namespace SumerCoreDevOps.ControlApi.Controllers;

/// <summary>
/// 任务管理接口
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class TaskController : ControllerBase
{
    private readonly FreeSQLProvider _dbProvider;
    private readonly WorkflowInstanceTracker _instanceTracker;
    private readonly ILogger<TaskController> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="dbProvider">数据库提供者</param>
    /// <param name="instanceTracker">工作流实例跟踪器</param>
    /// <param name="logger">日志记录器</param>
    public TaskController(
        FreeSQLProvider dbProvider,
        WorkflowInstanceTracker instanceTracker,
        ILogger<TaskController> logger)
    {
        _dbProvider = dbProvider;
        _instanceTracker = instanceTracker;
        _logger = logger;
    }

    /// <summary>
    /// 获取流水线实例详情
    /// </summary>
    /// <param name="id">实例ID</param>
    /// <returns>返回指定流水线实例的完整信息对象,包括实例ID、流水线ID、状态、开始时间、结束时间、提交信息等;如果实例不存在则返回404状态码和失败信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回实例信息</response>
    /// <response code="404">实例不存在</response>
    [HttpGet("instance/{id}")]
    [ProducesResponseType(typeof(ApiResponse<PipelineInstance>), 200)]
    [ProducesResponseType(typeof(ApiResponse<object>), 404)]
    
    public async Task<IActionResult> GetInstance(long id)
    {
        var instance = await _instanceTracker.GetInstanceAsync(id);

        if (instance == null)
        {
            return NotFound(ApiResponse.Fail($"实例 {id} 不存在"));
        }

        return Ok(ApiResponse.Ok(instance));
    }

    /// <summary>
    /// 获取实例的所有任务列表
    /// </summary>
    /// <param name="id">流水线实例ID</param>
    /// <returns>返回指定流水线实例下的所有任务列表,每个任务包含任务ID、名称、状态、执行节点、开始时间、结束时间等信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回任务列表</response>
    [HttpGet("instance/{id}/tasks")]
    [ProducesResponseType(typeof(ApiResponse<List<TaskEntity>>), 200)]
    public async Task<IActionResult> GetInstanceTasks(long id)
    {
        var tasks = await _instanceTracker.GetInstanceTasksAsync(id);
        return Ok(ApiResponse.Ok(tasks));
    }

    /// <summary>
    /// 获取实例统计信息
    /// </summary>
    /// <param name="id">流水线实例ID</param>
    /// <returns>返回流水线实例的统计信息对象,包括任务总数、成功任务数、失败任务数、运行中任务数、平均执行时间等统计数据;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回统计信息</response>
    [HttpGet("instance/{id}/statistics")]
    [ProducesResponseType(typeof(ApiResponse<InstanceStatistics>), 200)]
    public async Task<IActionResult> GetInstanceStatistics(long id)
    {
        var statistics = await _instanceTracker.GetInstanceStatisticsAsync(id);
        return Ok(ApiResponse.Ok(statistics));
    }

    /// <summary>
    /// 获取正在运行的流水线实例列表
    /// </summary>
    /// <returns>返回当前所有正在运行中的流水线实例列表,每个实例包含实例ID、流水线名称、状态、开始时间、当前进度等信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回运行中的实例</response>
    [HttpGet("running")]
    [ProducesResponseType(typeof(ApiResponse<List<PipelineInstance>>), 200)]
    public async Task<IActionResult> GetRunningInstances()
    {
        var instances = await _instanceTracker.GetRunningInstancesAsync();
        return Ok(ApiResponse.Ok(instances));
    }

    /// <summary>
    /// 获取任务详细信息
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>返回指定任务的完整信息对象,包括任务ID、名称、状态、执行节点信息、流水线实例信息、开始时间、结束时间、日志路径等;如果任务不存在则返回404状态码和失败信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回任务信息</response>
    /// <response code="404">任务不存在</response>
    [HttpGet("{id}")]
    [ProducesResponseType(typeof(ApiResponse<TaskEntity>), 200)]
    [ProducesResponseType(typeof(ApiResponse<object>), 404)]
    public async Task<IActionResult> GetTask(long id)
    {
        var task = await _dbProvider.Orm.Select<TaskEntity>()
            .Where(t => t.Id == id)
            .Include(t => t.Node)
            .Include(t => t.PipelineInstance)
            .FirstAsync();

        if (task == null)
        {
            return NotFound(ApiResponse.Fail($"任务 {id} 不存在"));
        }

        return Ok(ApiResponse.Ok(task));
    }

    /// <summary>
    /// 获取任务执行日志
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>返回指定任务的执行日志完整文本内容;如果任务不存在则返回404状态码和失败信息;如果日志文件不存在或尚未生成则返回提示信息;数据封装在ApiResponse对象中</returns>
    /// <response code="200">成功返回日志内容</response>
    /// <response code="404">任务不存在</response>
    [HttpGet("{id}/logs")]
    [ProducesResponseType(typeof(ApiResponse<string>), 200)]
    public async Task<IActionResult> GetTaskLogs(long id)
    {
        var task = await _dbProvider.Orm.Select<TaskEntity>()
            .Where(t => t.Id == id)
            .FirstAsync();

        if (task == null)
        {
            return NotFound(ApiResponse.Fail($"任务 {id} 不存在"));
        }

        if (string.IsNullOrEmpty(task.LogPath) || !System.IO.File.Exists(task.LogPath))
        {
            return Ok(ApiResponse.Ok("日志文件不存在或尚未生成"));
        }

        var logs = await System.IO.File.ReadAllTextAsync(task.LogPath);
        return Ok(ApiResponse.Ok(logs));
    }
}
